package com.company.cyxmall.product.service.impl;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.company.cyxmall.product.service.CategoryBrandRelationService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.company.common.utils.PageUtils;
import com.company.common.utils.Query;

import com.company.cyxmall.product.dao.CategoryDao;
import com.company.cyxmall.product.entity.CategoryEntity;
import com.company.cyxmall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Resource
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }


    @Override
    public List<CategoryEntity> listToTree() {
        List<CategoryEntity> categories = baseMapper.selectList(null);

        /**
         *  Lv1Menus菜单
         * */
        List<CategoryEntity> Lv1Menus = categories.stream().filter((entity) -> {
            return entity.getParentCid() == 0;
        }).map((entity) -> {
            /**
             *  得到Lv1Menus菜单的子菜单（可能有N个）
             * */
            entity.setChildren( getChildrens(entity, categories) );
            return entity;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0:menu1.getSort()) - (menu2.getSort() == null ? 0:menu2.getSort());
        }).collect(Collectors.toList());

        return Lv1Menus;
    }
    /**
     *  递归查找子菜单
     * */
    private List<CategoryEntity> getChildrens (CategoryEntity root, List<CategoryEntity> all){
        List<CategoryEntity> children = all.stream().filter((entity) -> {
            /**
             *  Lv2Menus菜单
             * */
            return entity.getParentCid() == root.getCatId();
        }).map((entity) -> {
            /**
             *  Lv3Menus菜单
             * */
            entity.setChildren( getChildrens(entity, all) );
            return entity;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0:menu1.getSort()) - (menu2.getSort() == null ? 0:menu2.getSort());
        }).collect(Collectors.toList());
        return children;
    }


    @Override
    public void removeMenuByIds(List<Long> idList) {
        //TODO  1.检查要删除的菜单是否有被引用
        baseMapper.deleteBatchIds(idList);
    }


    @Override
    public Long[] findCategoryPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }
    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity entity = this.getById(catelogId);
        if (entity.getParentCid() != 0) {
            findParentPath(entity.getParentCid(), paths);
        }
        return paths;
    }


    @Override
    @Transactional
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

}